
// export const postURL = "https://baotuite.iceand.cn/api/"
export const staticURL = ""
export const postURL = "http://159.75.233.104/index/"
export const imgURL = 'http://127.0.0.1:8000/uniapp/'

import Vue from 'vue'




const login_num ="baiyanjing_login_num"
function setHeader(isfile){
	let token = uni.getStorageSync('baiyanjing_login_token');

	let header = {'content-type':'application/json'}

	if(token){
		header = {'Api-Token':token,'content-type':'application/json'}
	}
	if(isfile){
		header = {'Api-Token':token}
	}

	return header
}
export const getToken = (()=>{
    let token = uni.getStorageSync('baiyanjing_login_token');
    return token
})
export const loginout = (()=>{
    uni.removeStorageSync('baiyanjing_login_token')
})
//统一响应
function response(response,resolve,reject){
	uni.hideLoading();
	
	var data = response.data

	if(data.code==0){
		uni.showToast({
			title: data.info,
			icon: 'none',
            duration:2000,
			success() {
                
			}
		});
		if(data.data.url){
            setTimeout(function(){
                uni.navigateTo({
                	url:data.data.url
                })
            },2000)
        }
		return false
	}else if(data.code==3){
		uni.navigateTo({
			url:`/pages/login/index`
		})
		return false
	}else{
	
		return data	
	}
}

function getRandomString(length) {
  var result = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
/**
 * @title 生产签名
 * @param {Object} data
 */
function geiSign(data){
    let params = {appid: 'uni.plantreenew.com', appkey: 'ice.and.lee'};
    let postdata = data;
    
    // 接口请求数据组装
    let nostr = getRandomString(10);
    let time = Math.ceil(Date.now() / 1000);
    let sign
    if(postdata){
        var newData = {}
        for(let i in postdata) {  // 给 obj 对象做循环;
            
            if(typeof postdata[i] !='array' && typeof postdata[i]!='object'){
                console.log(i!="timestamp" && i!="nostr" && i!="sign")
                if(i!="timestamp" && i!="nostr" && i!="sign"){
                    newData[i] = postdata[i]+''
                }
            }else{
                newData[i] = postdata[i]
            }
        }
     
        let json = JSON.stringify(newData);
        console.log([params.appid, json, time, params.appkey, nostr].join('#'))
        sign = md5.hex_md5([params.appid, json, time, params.appkey, nostr].join('#'));
    }else{
        sign = md5.hex_md5([params.appid, time, params.appkey, nostr].join('#'));
        data = {}
    }
        
    data['timestamp'] = time;
    data['nostr'] = nostr
    data['sign'] = sign
    return data;
}
export const myPost = ((url,data)=>{
    
	return new Promise((resolve, reject)=>{
		uni.getNetworkType({
			success:function(res){
				if(res.networkType=="none"){
					uni.showToast({
						title:'当前无网络'
					})
					reject("当前无网络")
				}else{
					uni.showLoading()
					uni.request({
						url:postURL + url,
						method:"POST",
						data: data,
						header:setHeader(false),
						success:(res)=>{
							let r = response(res)
							if(!r){
								reject("请登录")
							}else{
							
								resolve(r)
							}
						},
						fail:(err)=>{
							uni.showToast({
								title:'请求接口失败',
								icon:"none"
							})
							reject(err)
						}
					})
				}
			
			}
		})
	
	})
	
})


export const myGet = function(url,data){
	return new Promise((resolve, reject)=>{
		uni.getNetworkType({
			success:function(res){
			
				if(res.networkType=="none"){
					uni.showToast({
						title:'当前无网络'
					})
					reject("当前无网络")
				}else{
					uni.showLoading()
					uni.request({
						url:postURL + url,
						method:"GET",
						data: data,
						header:setHeader(false),
						success:(res)=>{
							let r = response(res)
							if(!r){
								reject("请登录")
							}else{
							
								resolve(r)
							}
						},
						fail:(err)=>{
							uni.showToast({
								title:'请求接口失败'
							})
							reject(err)
						}
					})
				}
			
			}
		})
	
	})
}
export const uploadfile = function(url,data,formData){
	return new Promise((resolve, reject)=>{
		uni.getNetworkType({
			success:function(res){
			
				if(res.networkType=="none"){
					uni.showToast({
						title:'当前无网络'
					})
					reject("当前无网络")
				}else{
					uni.showLoading()
					
					uni.uploadFile({
						url:postURL + url,
						filePath: data,
						name:"file",
                        formData:formData,
						header:setHeader(true),
						success: (res) => {
	
							res.data = JSON.parse(res.data)
							let r = response(res)
							if(!r){
								reject("请登录")
							}else{
							
								resolve(r)
							}
						},
						fail:(err)=>{
							uni.showToast({
								title:'请求接口失败'
							})
							reject(err)
						}
					});
				
				}
			
			}
		})
	
	})
}
export function countDown (endtimes){
	var nowtime = new Date();
	var endtime = new Date(endtimes);
	var lefttime = parseInt((endtime.getTime() - nowtime.getTime()) / 1000);
	var d = parseInt(lefttime/(60 * 60 * 24))
	
	var h = parseInt(lefttime/(60 * 60) );
	var m = parseInt(lefttime / 60 % 60);
	var s = parseInt(lefttime % 60);
	if(h>0){
		h=(h>=10?h:"0"+h)  
	}else{
		h = "00"
	}			
	if(m>0){
		m=(m>=10?m:"0"+m)  
	}else{
		m = "00"
	}
	if(s>0){
		s=(s>=10?s:"0"+s)  
	}else{
		s = "00"
	}
	
	return {d:d,h:h,m:m,s:s,lefttime:lefttime}
}


export default {myPost,myGet,postURL,countDown,uploadfile,loginout,getToken,imgURL};